/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.dataie.service;

import java.io.File;
import java.util.ArrayList;

import javax.persistence.EntityManager;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;

import com.ibm.iisp.common.util.BeanFactory;
import com.ibm.iisp.common.util.FileStoreUtils;
import com.ibm.iisp.common.util.StringUtilsExt;
import com.ibm.iisp.dataie.vo.DataExportRequest;

/**
 * 类作用：无定制模板导出数据
 * 
 * @author Johnny@cn.ibm.com 使用说明：
 */
public class DefaultExcelDataExporter extends ExcelDataExporter {
	/**
	 * @param dataExportReq
	 * @param dao
	 */
	public DefaultExcelDataExporter(DataExportRequest dataExportReq, EntityManager dao) {
		super(dataExportReq, dao);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ibm.iisp.dataie.service.AbstractDataExporter#init()
	 */
	@Override
	public String init() {
		parseFilterParams();
		// 为更好的兼容性，缺省生成xls文件，不用xlsx
		this.book = new HSSFWorkbook();
		this.sheet = book.createSheet("DATA");
		Row r0 = sheet.createRow(0);
		r0.createCell(0).setCellValue(dataExportReq.getTableName());
		r0.createCell(1).setCellValue(StringUtilsExt.MD5(dataExportReq.getTableName()));
		r0.setZeroHeight(true);
		// 第二行：列名，第三行：列中文名
		ArrayList<String> row2 = new ArrayList<>(dataExportReq.getColumns().size());
		ArrayList<String> row3 = new ArrayList<>(dataExportReq.getColumns().size());
		for (DataExportRequest.ColumnDef col : dataExportReq.getColumns()) {
			if (Boolean.TRUE.equals(col.getIsExport())) {
				row2.add(col.getName());
				String desc = col.getDesc();
				if (desc == null) {
					desc = col.getName();
				}
				if (Boolean.TRUE.equals(col.getIsRequired())) {
					desc = "*" + desc;
				}
				row3.add(desc);
			}
		}
		writeSheetRow(row2);
		writeSheetRow(row3);

		// 生成文件名，以便输出excel文件内容
		String rfilePath = DATA_EXP_FILE_ROOT;
		BeanFactory beanFactory = BeanFactory.getInstance();
		FileStoreUtils fileStoreUtils = beanFactory.getBean(FileStoreUtils.class);
		String absFilePath = fileStoreUtils.getAbsFilePath(rfilePath);
		this.dataFile = new File(absFilePath);
		dataFile.mkdirs();
		String dName = dataExportReq.getFileName();
		if (StringUtils.isNotEmpty(dName)) {
			// 如果没有扩展名，则加上
			if (dName.indexOf(".") < 0) {
				dName += ".xls";
			}
		} else {
			dName = dataExportReq.getTableName() + ".xls";
		}
		String encodeFileName = fileStoreUtils.encodeFileName(dName);
		rfilePath += "/" + encodeFileName;
		absFilePath = absFilePath + "/" + encodeFileName;
		this.dataFile = new File(absFilePath);
		return absFilePath;
	}

	/**
	 * @param rowVals
	 */
	protected void writeSheetRow(ArrayList<String> rowVals) {
		Row row = sheet.createRow(sheet.getLastRowNum() + 1);
		for (int i = 0; i < rowVals.size(); i++) {
			row.createCell(i).setCellValue(rowVals.get(i));
		}
	}


}
